package com.association.main.controller;

import com.association.main.common.R;
import com.association.main.domain.*;
import com.association.main.dto.EventsDto;
import com.association.main.service.ClubsService;
import com.association.main.service.EventsService;
import com.association.main.service.SignupsService;
import com.association.main.service.UsersService;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/events")
public class EventsController {
    @Autowired
    private EventsService eventsService;
    @Autowired
    private UsersService usersService;

    @Autowired
    private ClubsService clubsService;

    @Autowired
    private SignupsService signupsService;

    /*
     * 首页分页查询
     * */
    @GetMapping
    public R<Page> eventsList(int page, int pageSize, Integer clubId,String name,HttpServletRequest request) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Events> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(clubId != null, Events::getClubId, clubId);
        lambdaQueryWrapper.like(name!=null,Events::getName,name);
        List<Events> list = eventsService.list(lambdaQueryWrapper);
        eventsService.page(pageInfo, lambdaQueryWrapper);

        List<EventsDto> eventsDtoList = list.stream().map((item) -> {
            EventsDto eventsDto = new EventsDto();
            BeanUtils.copyProperties(item, eventsDto);
            Clubs clubs = clubsService.getById(item.getClubId());
            Users users = usersService.getById(item.getCreatedBy());
            eventsDto.setUsers(users);
            eventsDto.setClubs(clubs);
            LambdaQueryWrapper<Signups> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(Signups::getEventId,item.getId());
            int count = signupsService.count(lambdaQueryWrapper1);
            eventsDto.setCount(count);
            return eventsDto;
        }).collect(Collectors.toList());

        // 处理权限问题
        String token = request.getHeader("token");
        String userType = JwtUtil.getUserType(token);
        if ("member".equals(userType)) {
            Integer userId = JwtUtil.getUserId(token);
            LambdaQueryWrapper<Clubs> clubsWrapper = new LambdaQueryWrapper<>();
            clubsWrapper.eq(Clubs::getCreatedBy, userId);
            List<Clubs> clubsList = clubsService.list(clubsWrapper);
            eventsDtoList = eventsDtoList.stream().filter(m -> clubsList.stream().anyMatch(c -> m.getClubs().equals(c))).collect(Collectors.toList());
        }


        pageInfo.setRecords(eventsDtoList);
        return R.success(pageInfo);
    }

    @PostMapping
    public R<Events> add(@RequestBody Events events, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        events.setStatus(0);
        events.setCreatedAt(LocalDateTime.now());
        events.setUpdatedAt(LocalDateTime.now());
        events.setCreatedBy(userId);
        boolean save = eventsService.save(events);
        return save == true ? R.success(events) : R.error("添加失败，未知错误");
    }

    @PutMapping
    public R<String> update(@RequestBody Events events) {
        boolean update = eventsService.updateById(events);
        return update == true ? R.success("修改成功") : R.error("修改失败，未知错误");
    }

    @DeleteMapping
    public R<String> delete(@RequestBody Events events) {
        boolean delete = eventsService.removeById(events.getId());
        return delete == true ? R.success("删除成功") : R.error("删除失败，未知错误");
    }



    @PostMapping("/status")
    public R<String> eventsStatus( int id, int status){
        LambdaUpdateWrapper<Events> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Events::getId,id).set(Events::getStatus,status);
        boolean success = eventsService.update(lambdaUpdateWrapper);
        if (success) {
            return R.success("审核成功");
        } else {
            return R.error("审核失败");
        }
    }

}
